﻿using System;
using System.Collections.Generic;
using System.Linq;
using Interfaces;
using PeopleEntity;
using PeopleException;

namespace PeopleBll
{
    public class NewsBll : INewsBll
    {
        private readonly INews _news;

        public NewsBll(INews news)
        {
            _news = news;
        }

        public bool Create(string title, string content, DateTime publishDate)
        {
            var result = false;
            try
            {
                var news = new News(publishDate, title, content);
                result = _news.Create(news);
            }
            catch (Exception e)
            {
                var ex = string.Format("Exception in wok logic layer: {0}", e.Message);
                throw new BllException(ex);
            }
            return result;
        }

        public List<ViewNews> ReadAll()
        {
            List<ViewNews> lst = null;
            try
            {
                lst = _news.ReadAll().Select(ToViewNews).ToList();
            }
            catch (Exception e)
            {
                var ex = string.Format("Exception in wok logic layer: {0}", e.Message);
                throw new BllException(ex);
            }
            return lst;
        }


        public List<ViewNews> ReadSomeNews()
        {
            List<ViewNews> lst = null;
            const int toDelete = 10;
            try
            {
                lst = ReadAll();
                if (lst.Count > 10)
                    lst.RemoveRange(toDelete, lst.Count - toDelete);
            }
            catch (Exception e)
            {
                var ex = string.Format("Exception in wok logic layer: {0}", e.Message);
                throw new BllException(ex);
            }
            return lst;
        }

        public News Read(Guid id)
        {
            News news = null;
            try
            {
                news=_news.Read(id);
            }
            catch (Exception e)
            {
                var ex = string.Format("Exception in wok logic layer: {0}", e.Message);
                throw new BllException(ex);
            }
            return news;
        }

        private static ViewNews ToViewNews(News news)
        {
            const int toDelete = 50;
            if (news.Content.Length > toDelete)
                return new ViewNews { Id = news.Id, Content = news.Content.Remove(toDelete), Date = news.Date, Title = news.Title };
            return new ViewNews { Id = news.Id, Content = news.Content, Date = news.Date, Title = news.Title };
        }
    }
}
